﻿package net.wangit.adm.role;

import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.LocalContext;
import net.wangit.support.UnitInterceptor;
import net.wangit.user.role.Role;
import net.wangit.user.role.RoleFactory;
import net.wangit.util.Checker;
import net.wangit.view.unit.UnitComponent;

public class RolePrivilegeUI implements UnitInterceptor {

	private static final String DOMAIN = "net.wangit.adm.role.RoleHelper.domain";
	public static final String ROLE_ID = "net.wangit.adm.role.RoleHelper.roleid";

	public RolePrivilegeUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String roleId = getAndSetRoleId();
		if (Checker.isEmpty(roleId)) {
			return "";
		} else {
			unit.getElement("domain").setDefaultValue(getAndSetDomain());
			unit.getElement("roleid").setDefaultValue(roleId);
			Role role = RoleFactory.getRole(roleId);
			unit.setTitle((new StringBuilder(String
					.valueOf(((UnitComponent) unit).getTitle()))).append(" - ")
					.append(role.getName()).append("(").append(roleId).append(
							")").toString());
			return unit.write(ac);
		}
	}

	public static String getAndSetDomain() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac,
				"role.privileges.domain",
				"net.wangit.adm.role.RoleHelper.domain", "app");
	}

	public static String getDomain(ActionContext ac) {
		return (String) ac
				.getSessionAttribute("net.wangit.adm.role.RoleHelper.domain");
	}

	public static String getRoleId(ActionContext ac) {
		return (String) ac
				.getSessionAttribute("net.wangit.adm.role.RoleHelper.roleid");
	}

	public static String getAndSetRoleId() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac, "roleid",
				"net.wangit.adm.role.RoleHelper.roleid", null);
	}
}
